<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>包头希望铝业电解铝车间管理 - {{ sectionName }} - 槽位状态详情</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text" 
          icon="el-icon-refresh"
          @click="loadSlotData(true)"
          :loading="loading"
        >刷新</el-button>
      </div>
      
      <!-- 槽位状态统计 -->
      <div class="status-summary">
        <el-row :gutter="20">
            <el-col :span="4">
            <div class="summary-card">
              <div class="summary-title">工段名称</div>
              <div class="summary-value">{{ sectionName }} 槽号：{{ sectionInfo.startSlotNo }}-{{ sectionInfo.endSlotNo }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="summary-card">
              <div class="summary-title">总槽数</div>
              <div class="summary-value">{{ sectionInfo.slotCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="summary-card">
              <div class="summary-title">异常槽数</div>
              <div class="summary-value error">{{ errorSlotCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="summary-card">
              <div class="summary-title">下料点位</div>
              <div class="summary-value success">{{ dischargePointCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="summary-card">
              <div class="summary-title">卡堵点位</div>
              <div class="summary-value warning">{{ jamPointCount }}</div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="summary-card">
              <div class="summary-title">实时报警</div>
              <div class="summary-value warning">
                <el-button 
                type="info"
                plain
                icon="el-icon-bell"
                size="mini"
                @click="showAlarmWindow = true"
              > 查看报警 </el-button>
              </div>
              
            </div>
          </el-col>
        </el-row>
      </div>
      
      <!-- 槽位网格展示 -->
      <div class="slot-grid">
        <slot-card 
          v-for="slot in slotList" 
          :key="slot.slotNumber"
          :slot-data="slot"
          @open-setting="handleOpenSetting"
        />
      </div>
    </el-card>

    <!-- 槽位设置对话框 - 放在最外层避免因组件更新导致闪烁 -->
    <slot-setting-dialog
      :visible.sync="settingDialogVisible"
      :slot-number="currentSlotNumber"
      :points-per-slot="pointsPerSlot"
      :section-name="sectionName"
    />

    <!-- 实时报警通知悬浮窗口 -->
    <alarm-notification 
      v-if="showAlarmWindow"
      ref="alarmNotification" 
      :max-alarms="50"
      @close="showAlarmWindow = false"
    />
  </div>
</template>

<script>
import { getSectionSlots } from "@/api/workshop/section";
import SlotCard from "../components/SlotCard";
import SlotSettingDialog from "../components/SlotSettingDialog";
import AlarmNotification from "../components/AlarmNotification";

export default {
  name: "SectionDetail",
  components: {
    SlotCard,
    SlotSettingDialog,
    AlarmNotification
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 定时器
      refreshTimer: null,
      // 工段名称
      sectionName: '',
      // 工段基本信息
      sectionInfo: {
        startSlotNo: 0,
        endSlotNo: 0,
        pointsPerSlot: 0
      },
      // 槽位列表
      slotList: [],
      // 设置对话框显示状态
      settingDialogVisible: false,
      // 当前选中的槽位编号
      currentSlotNumber: null,
      // 当前选中槽位的点位数
      pointsPerSlot: 4,
      // 实时报警窗口显示状态
      showAlarmWindow: false
    };
  },
  computed: {
    // 异常槽数
    errorSlotCount() {
      return this.slotList.filter(slot => {
        return slot.powerBoxDoorOpen || slot.controllerDoorOpen;
      }).length;
    },
    // 下料点位数量
    dischargePointCount() {
      let count = 0;
      this.slotList.forEach(slot => {
        if (slot.pointInfos) {
          count += slot.pointInfos.filter(point => point.dischargeStatus).length;
        }
      });
      return count;
    },
    // 卡堵点位数量
    jamPointCount() {
      let count = 0;
      this.slotList.forEach(slot => {
        if (slot.pointInfos) {
          count += slot.pointInfos.filter(point => point.jamStatus).length;
        }
      });
      return count;
    }
  },
  created() {
    this.sectionName = this.$route.query.sectionName || '';
    this.getSectionInfo();
    this.loadSlotData();
    // 启动定时刷新
    this.startAutoRefresh();
  },
  beforeDestroy() {
    // 清理定时器
    this.stopAutoRefresh();
  },
  methods: {
    /** 从工段对象获取基本信息 */
    getSectionInfo() {
      // 根据工段名称获取基本信息
      const sectionMap = {
        '11段': { startSlotNo: 1001, endSlotNo: 1075, slotCount: 75, pointsPerSlot: 4 },
        '12段': { startSlotNo: 1076, endSlotNo: 1151, slotCount: 76, pointsPerSlot: 4 },
        '21段': { startSlotNo: 2001, endSlotNo: 2075, slotCount: 75, pointsPerSlot: 4 },
        '22段': { startSlotNo: 2076, endSlotNo: 2151, slotCount: 76, pointsPerSlot: 4 },
        '31段': { startSlotNo: 3001, endSlotNo: 3075, slotCount: 75, pointsPerSlot: 4 },
        '32段': { startSlotNo: 3076, endSlotNo: 3151, slotCount: 76, pointsPerSlot: 4 },
        '41段': { startSlotNo: 4001, endSlotNo: 4075, slotCount: 75, pointsPerSlot: 4 },
        '42段': { startSlotNo: 4076, endSlotNo: 4151, slotCount: 76, pointsPerSlot: 4 },
        '51段': { startSlotNo: 5001, endSlotNo: 5077, slotCount: 77, pointsPerSlot: 6 },
        '52段': { startSlotNo: 5078, endSlotNo: 5154, slotCount: 77, pointsPerSlot: 6 },
        '61段': { startSlotNo: 6001, endSlotNo: 6077, slotCount: 77, pointsPerSlot: 6 },
        '62段': { startSlotNo: 6078, endSlotNo: 6154, slotCount: 77, pointsPerSlot: 6 }
      };
      
      this.sectionInfo = sectionMap[this.sectionName] || { 
        startSlotNo: 0, 
        endSlotNo: 0, 
        slotCount: 0, 
        pointsPerSlot: 0 
      };
    },
    
    /** 加载槽位数据 */
    loadSlotData(showMessage = false) {
      this.loading = true;
      getSectionSlots(this.sectionName).then(response => {
        this.slotList = response.data || [];
        this.loading = false;
        if (showMessage) {
          this.$message.success('数据刷新成功');
        }
      }).catch(() => {
        this.slotList = [];
        this.loading = false;
        if (showMessage) {
          this.$message.error('数据刷新失败');
        }
      });
    },
    
    /** 启动自动刷新 */
    startAutoRefresh() {
      // 清除现有定时器
      this.stopAutoRefresh();
      // 设置1秒定时刷新
      this.refreshTimer = setInterval(() => {
        this.loadSlotData(false); // 定时刷新不显示消息
      }, 1000);
    },
    
    /** 停止自动刷新 */
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },
    /** 处理打开设置对话框 */
    handleOpenSetting(slotData) {
      this.currentSlotNumber = slotData.slotNumber;
      // 从槽位数据获取点位数，优先使用 pointsPerSlot，否则使用 pointInfos 的长度
      this.pointsPerSlot = slotData.pointsPerSlot || 
                                   (slotData.pointInfos && slotData.pointInfos.length) || 
                                   4;
      this.settingDialogVisible = true;
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 5px 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.box-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.box-card .el-card__body {
  padding: 8px 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.section-info {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.info-item .label {
  font-weight: bold;
  color: #606266;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
  font-size: 16px;
}

.status-summary {
  margin-top: 0;
  margin-bottom: 12px;
  flex-shrink: 0;
}

.summary-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 12px;
  text-align: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.summary-title {
  color: #909399;
  font-size: 12px;
  margin-bottom: 6px;
}

.summary-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.summary-value.error {
  color: #f56c6c;
}

.summary-value.success {
  color: #67c23a;
}

.summary-value.warning {
  color: #e6a23c;
}

.slot-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  max-height: calc(100vh - 200px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .slot-grid {
    grid-template-columns: 1fr;
  }
  
  .header-actions {
    float: none;
    margin-top: 10px;
  }
}
</style>
